package com.zhang.third.day10;

/**
 * @title: 归并排序
 * @author: zhang
 * @date: 2022/4/15 19:57
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {3, 2, 1, 5, 4, 7, 6};
        process(arr, 0, arr.length - 1);
        for (int i : arr) {
            System.out.println(i);
        }
    }

    public static void process(int[] arr, int L, int R) {
        if (L == R || arr == null || arr.length < 2) {
            return;
        }
        int mid = L + ((R - L) >> 1);
        process(arr, L, mid);
        process(arr, mid + 1, R);

        merge(arr, L, mid, R);
    }

    public static void merge(int[] arr, int L, int M, int R) {
        int[] help = new int[R - L + 1];
        int i = 0;
        int p1 = L;
        int p2 = M + 1;
        while (p1 <= M && p2 <= R) {
            help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= M) {
            help[i++] = arr[p1++];
        }
        while (p2 <= R) {
            help[i++] = arr[p2++];
        }
        for (int j = 0; j < help.length; j++) {
            arr[L + j] = help[j];
        }

    }
}
